package com.jdyfy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jdyfy.dto.NoshowCountDTO;
import com.jdyfy.entity.*;
import com.jdyfy.result.Result;
import com.jdyfy.service.AnnouncementDepartmentService;
import com.jdyfy.service.DepartmentService;
import com.jdyfy.service.NotificationService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/jdyfy")
@Slf4j
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private NotificationService notificationService;


    @Resource
    private AnnouncementDepartmentService announcementDepartmentService;

    // 新增或修改部门信息
    @PostMapping("/department/save")
    public boolean addOrUpdateDepartment(@RequestBody Department department) {
        boolean b = departmentService.saveOrUpdate(department);
        if(b && department.getDepartmentNumber() == null){
            Notification notification = Notification.builder()
                    .message("您好，您的企业注册已成功，欢迎您。(温馨提示，请完善您的企业信息哦！)")
                    .type("注册提醒")
                    .timestamp(LocalDateTime.now())
                    .departmentName(department.getDepartmentName())
                    .isRead(0)  // 未读
                    .handleStatus(0)  // 未处理
                    .build();
            notificationService.saveOrUpdate(notification);
        }
        return b;
    }

    // 企业报名公告的信息
    @PostMapping("/annouDepart")
    public boolean addAnnouDepartment(@RequestBody AnnouncementDepartment ad){
        boolean b = announcementDepartmentService.saveOrUpdate(ad);
        if(b){
            int startIdx2 = ad.getAnnouncementName().indexOf("+") + 1; // 获取 + 后的位置
            int endIdx2 = ad.getAnnouncementName().indexOf("}", startIdx2); // 获取第二个 } 的位置
            String projectName = ad.getAnnouncementName().substring(startIdx2, endIdx2); // 提取 + 和 } 之间的部分
            Notification notification = Notification.builder()
                    .message(String.format("您好，您参加的{%s}已报名成功，请留意后续消息。", projectName))
                    .type("报名提醒")
                    .timestamp(LocalDateTime.now())
                    .departmentName(ad.getDepartmentName())
                    .isRead(0)  // 未读
                    .handleStatus(0)  // 未处理
                    .build();
            notificationService.saveOrUpdate(notification);
        }


        announcementDepartmentService.getEnrollCount(ad.getAnnouncementName()); // 查询该公告报名企业数量，如果达到三，则修改项目状态
        return  b;
    }

    // 通过企业名称查询企业信息
    @GetMapping("/department/getDepartByDepartName")
    public Result<Department> getDepartByDepartName(@RequestParam String departmentName){
        Department department = departmentService.getByDepartName(departmentName);
        return Result.success(department);
    }

    // 通过企业名称查询企业信息
    @PostMapping("/department/getDepartsByDepartNames")
    public Result<List<Department>> getDepartsByDepartNames(@RequestBody List<String> departNames){
        return Result.success(departmentService.getDepartsByDepartNames(departNames));
    }

    //供应商分页
    @GetMapping("/supplerPage")
    public Result<Map<String, Object>> getSupplerPage(@RequestParam Integer pageNum,
                                                      @RequestParam Integer pageSize,
                                                      @RequestParam String departmentName,
                                                      @RequestParam String departmentNumber) {
        List<Department> list = departmentService.getSuppler(departmentName, departmentNumber);

        // 获取总记录数
        int totalCount = list.size();

        // 计算分页后的数据
        List<Department> paginatedList = getPaginatedDepartments(list, pageNum, pageSize);

        // 计算总页数
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);

        // 将分页信息和分页数据封装在一个 Map 中
        Map<String, Object> result = new HashMap<>();
        result.put("records", paginatedList);
        result.put("pages", totalPages);
        result.put("current", pageNum);
        result.put("size", pageSize);
        result.put("total", totalCount);  // 返回符合条件的总记录数

        return Result.success(result);
    }

    // 分页算法
    public List<Department> getPaginatedDepartments(List<Department> list, int pageNumber, int pageSize) {
        int fromIndex = (pageNumber - 1) * pageSize;
        if (fromIndex >= list.size()) {
            return List.of(); // 超出范围时返回空列表
        }
        int toIndex = Math.min(fromIndex + pageSize, list.size());
        return list.subList(fromIndex, toIndex);
    }

    // 新增或修改爽约信息
    @PostMapping("/department/noshow")
    public boolean addOrUpdateNoshow(@RequestBody DepartmentNoshow departmentNoshow) {
        return departmentService.addOrUpdate(departmentNoshow) ;
    }

    // 供应商总数
    @GetMapping("/department/getSuppler")
    public Result<Long> getSuppler(){
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_role", "供应商");
        return Result.success(departmentService.count(queryWrapper));
    }

    // 供应商爽约记录
    @GetMapping("/department/noshowByDepartmentPage")
    public Result<Map<String, Object>> getNoshowByDepartmentPage(
            @RequestParam Integer pageNumn,
            @RequestParam Integer pageSizen,
            @RequestParam String departmentName){
        //先根据特定条件查询出数据
        List<NoshowCountDTO> list = departmentService.getNoshowByDepartment(departmentName);

        // 获取总记录数
        int total = list.size();

        // 计算分页后的数据
        List<NoshowCountDTO> records = getPaginatedNoshows(list, pageNumn, pageSizen);

        // 计算总页数
        int pages = (int) Math.ceil((double) total / pageSizen);

        // 将分页信息和分页数据封装在一个 Map 中
        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        result.put("pages", pages);
        result.put("current", pageNumn);
        result.put("size", pageSizen);
        result.put("total", total);  // 返回符合条件的总记录数

        return Result.success(result);
    }

    // 分页查询方法
    public List<NoshowCountDTO> getPaginatedNoshows(List<NoshowCountDTO> list, int pageNumber, int pageSize) {
        int fromIndex = (pageNumber - 1) * pageSize;
        if (fromIndex >= list.size()) {
            return List.of(); // 超出范围时返回空列表
        }
        int toIndex = Math.min(fromIndex + pageSize, list.size());
        return list.subList(fromIndex, toIndex);
    }

}
